﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using YouWei.Utility.Logging;
using System.Web;

namespace YouWei.Utility
{
    /// <summary>
    /// web请求
    /// </summary>
    public class HttpWebRequestService
    {
        /// <summary>
        /// 获取web请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parmData">参数信息</param>
        /// <param name="contentType">HTTP头信息</param>
        /// <param name="headers">header</param>
        /// <returns></returns>
        public static string GetRequest(string url, string parmData, string contentType, Dictionary<string, string> headers)
        {
            string htmlContent = "";
            HttpWebRequest request;

            try
            {
                Encoding encoding = Encoding.GetEncoding("UTF-8");

                request = GetWebRequest(url, contentType);

                //请求方法
                request.Method = "GET";

                request.CookieContainer = new CookieContainer();

                //是否允许重定向
                request.AllowAutoRedirect = true;

                if (headers != null)
                {
                    foreach (var kvp in headers)
                    {
                        request.Headers.Add(kvp.Key, kvp.Value);
                    }
                }


                //设置请求字符长度
                byte[] buffer = encoding.GetBytes(parmData);
                request.ContentLength = buffer.Length;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //获取请求的返回信息
                Stream resSteam = response.GetResponseStream();
                StreamReader sr = new StreamReader(resSteam);
                htmlContent = sr.ReadToEnd();

                resSteam.Close();
            }
            catch (WebException wex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(wex.Message);
                sb.AppendLine(wex.StackTrace);
                sb.AppendLine(wex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            catch (InvalidOperationException ioex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ioex.Message);
                sb.AppendLine(ioex.StackTrace);
                sb.AppendLine(ioex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            finally
            {
                request = null;
            }

            return htmlContent;
        }

        /// <summary>
        /// 获取web请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">参数信息</param>
        /// <param name="contentType">HTTP头信息</param>
        /// <returns></returns>
        public static string PostRequest(string url, string postData, string contentType)
        {
            string htmlContent = "";
            HttpWebRequest request;

            try
            {
                Encoding encoding = Encoding.GetEncoding("UTF-8");

                request = GetWebRequest(url, contentType);

                //请求方法
                request.Method = "POST";

                request.CookieContainer = new CookieContainer();

                //设置请求字符长度
                byte[] buffer = encoding.GetBytes(postData);
                request.ContentLength = buffer.Length;

                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //获取请求的返回信息
                Stream resSteam = response.GetResponseStream();
                StreamReader sr = new StreamReader(resSteam);
                htmlContent = sr.ReadToEnd();

                resSteam.Close();
            }
            catch (WebException wex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(wex.Message);
                sb.AppendLine(wex.StackTrace);
                sb.AppendLine(wex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            catch (InvalidOperationException ioex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ioex.Message);
                sb.AppendLine(ioex.StackTrace);
                sb.AppendLine(ioex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            finally
            {
                request = null;
            }

            return htmlContent;
        }

        /// <summary>
        /// 获取web请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">参数信息</param>
        /// <param name="contentType">HTTP头信息</param>
        /// <param name="cookieData">cookie</param>
        /// <returns></returns>
        public static string PostRequest(string url, Dictionary<string, string> postData, string contentType, Dictionary<string, string> cookieData)
        {
            string htmlContent = "";
            HttpWebRequest request;

            try
            {
                Encoding encoding = Encoding.GetEncoding("UTF-8");

                request = GetWebRequest(url, contentType);

                //请求方法
                request.Method = "POST";

                request.CookieContainer = new CookieContainer();
                if (cookieData != null)
                {
                    foreach (var kvp in cookieData)
                    {
                        request.CookieContainer.Add(new Cookie()
                        {
                            Domain = request.Host,
                            Name = kvp.Key,
                            Value = kvp.Value
                        });
                    }
                }


                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.1021.400 QQBrowser/9.0.2524.400";

                //设置请求字符长度
                string parmData = DictoryToParam(postData);
                byte[] buffer = encoding.GetBytes(parmData);
                request.ContentLength = buffer.Length;

                //将请求信息添加到请求
                if (request.Method.Equals("POST"))
                {
                    Stream reqStream = request.GetRequestStream();
                    reqStream.Write(buffer, 0, buffer.Length);
                    reqStream.Close();
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //获取请求的返回信息
                Stream resSteam = response.GetResponseStream();
                StreamReader sr = new StreamReader(resSteam);
                htmlContent = sr.ReadToEnd();

                resSteam.Close();
            }
            catch (WebException wex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(wex.Message);
                sb.AppendLine(wex.StackTrace);
                sb.AppendLine(wex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            catch (InvalidOperationException ioex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ioex.Message);
                sb.AppendLine(ioex.StackTrace);
                sb.AppendLine(ioex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            finally
            {
                request = null;
            }

            return htmlContent;
        }

        /// <summary>
        /// 获取web请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parmData">参数信息</param>
        /// <param name="accept">接收</param>
        /// <returns></returns>
        public static HttpWebResponse GetRequestImg(string url, string parmData, string accept)
        {
            HttpWebRequest request;

            try
            {
                Encoding encoding = Encoding.GetEncoding("UTF-8");

                request = GetWebRequest(url,"");
                request.Accept = accept;

                //请求方法
                request.Method = "GET";

                request.CookieContainer = new CookieContainer();              
                //是否允许重定向
                request.AllowAutoRedirect = true;

                //设置请求字符长度
                byte[] buffer = encoding.GetBytes(parmData);
                request.ContentLength = buffer.Length;

                return request.GetResponse() as HttpWebResponse;             
            }
            catch (WebException wex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(wex.Message);
                sb.AppendLine(wex.StackTrace);
                sb.AppendLine(wex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            catch (InvalidOperationException ioex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ioex.Message);
                sb.AppendLine(ioex.StackTrace);
                sb.AppendLine(ioex.Source);
                Log4netLog.Debug(sb.ToString());
            }
            finally
            {
                request = null;
            }

            return null;
        }


        /// <summary>
        /// 获取web请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        private static HttpWebRequest GetWebRequest(string url, string contentType)
        {
            HttpWebRequest request;
            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }

            //如果用户名不为空,则添加身份验证
            request.Credentials = CredentialCache.DefaultCredentials;

            //请求类型
            request.ContentType = string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType;

            //是否允许重定向
            request.AllowAutoRedirect = true;
            return request;
        }

        /// <summary>
        /// 数组转换成参数
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        private static string DictoryToParam(Dictionary<string, string> dic)
        {
            string str = "";
            foreach (var kvp in dic)
            {
                if (!string.IsNullOrEmpty(kvp.Value))
                {
                    str += "&" + kvp.Key + "=" + HttpUtility.UrlEncode(kvp.Value);
                }
            }
            return str.Substring(1);
        }
        
        ///// <summary>
        ///// JavaUrlEncode
        ///// </summary>
        ///// <param name="str"></param>
        ///// <returns></returns>
        //private static string UrlEncode(string strCode)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    byte[] byStr = Encoding.UTF8.GetBytes(strCode); //默认是System.Text.Encoding.Default.GetBytes(str)
        //    System.Text.RegularExpressions.Regex regKey = new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$");
        //    for (int i = 0; i < byStr.Length; i++)
        //    {
        //        string strBy = Convert.ToChar(byStr[i]).ToString();
        //        if (regKey.IsMatch(strBy))
        //        {
        //            //是字母或者数字则不进行转换  
        //            sb.Append(strBy);
        //        }
        //        else
        //        {
        //            sb.Append(@"%" + Convert.ToString(byStr[i], 16).ToUpper());//javaEncode（urlencode大写）
        //        }
        //    }
        //    return sb.ToString();
        //}
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }

}

